function varargout = Xglom(varargin)
% XGLOM MATLAB code for Xglom.fig
%      XGLOM, by itself, creates a new XGLOM or raises the existing
%      singleton*.
%
%      H = XGLOM returns the handle to a new XGLOM or the handle to
%      the existing singleton*.
%
%      XGLOM('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in XGLOM.M with the given input arguments.
%
%      XGLOM('Property','Value',...) creates a new XGLOM or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Xglom_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Xglom_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Xglom

% Last Modified by GUIDE v2.5 24-Apr-2013 16:38:56

%     Copyright © 2012-2013 Michael Eager <michael.eager@monash.edu> 
%
%     This file is part of Xglom.
% 
%     This is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
% 
%     This is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
% 
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @Xglom_OpeningFcn, ...
    'gui_OutputFcn',  @Xglom_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Xglom is made visible.
function Xglom_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Xglom (see VARARGIN)
global table
%global img
%global depth


% Choose default command line output for Xglom
handles.output = hObject;

%% Global environment variables
handles.Xglom_version= getenv('XGLOM_VERSION');
if isempty(handles.Xglom_version)
 [status handles.Xglom_version]=system('awk -F''='' ''/XGLOM_VERSION=/ {print $2}'' ./xglom.sh  | tr -d ''\n'' ');
 setenv('XGLOM_VERSION',handles.Xglom_version);
end
handles.LocalCache = fullfile(pwd,'Cache');
addpath(fullfile(pwd,'plugins'))

%% Check memory size, minimum is 5 GB of RAM
if(java.lang.Runtime.getRuntime.maxMemory/(1024*1024*1024) < 5 ) 
    warndlg('The maximum memory allocation is insufficient for Xglom.  Go to File->Preferences, then to section General->Jave Heap Memory to increase memory allocation. Recommended maximum heap memory size is 25 GB (25000 MB). You must close Xglom and MATLAB then restart. Press OK to continue.','!! Warning Low Memory !!')
end


%% GUI variables
handles.debug=0;
handles.modality=0;
handles.DatasetSelection=0; % new element in handles to show selected datasets
handles.currentProject='1008.2.18'; % defaults to Monash DaRIS project Multimodal kidney image analysis project
handles.DatasetListing=[];  % stores last dls output
handles.Img=[];  % stores the image between inspection and processing

%% GUI CONSTANTS
% Enable all checkboxes
handles.MRModalityCheckbox=1;
handles.CTModalityCheckbox=1;
handles.VMModalityCheckbox=1;
handles.OriginalImageCheckbox=1;
handles.FilteredImageCheckbox=1;
handles.ProcessedImageCheckbox=1;

%Daris script 'dls' output columns
handles.DLS_CIDCOL=4;
handles.DLS_MODALITY_COL= 5;
handles.DLS_DATE_COL=6;
handles.DLS_TIME_COL=7;
handles.DLS_SIZE_COL=8;
handles.DLS_OrigFilt_COL=9;
handles.DLS_Description_COL=10;

% DATASET TABLE Columns
handles.TABLE_COL.CID=1;
handles.TABLE_COL.OrigFilt=2;
handles.TABLE_COL.Description=3;
handles.TABLE_COL.SIZE=4;
handles.TABLE_COL.DATE=5;
handles.TABLE_COL.TIME=6;

% Modalities:
%  0  Inactive
%  1  MR
%  2  CT
%  3  VM
handles.MRmodality=1;
handles.CTmodality=2;
handles.VMmodality=3;

%% Inline functions
handles.cleanmsgbox = 'delete(findobj(hMsg,''string'',''OK''));delete(findobj(hMsg,''style'',''frame''));mpos= get(hMsg,''position'');set(hMsg,''position'',[mpos(1)+36 mpos(2)-48 mpos(3:4)] );drawnow;';
handles.cleanmsgboxtable = 'delete(findobj(hMsgTable,''string'',''OK''));delete(findobj(hMsgTable,''style'',''frame''));mpos= get(hMsgTable,''position'');set(hMsgTable,''position'',[mpos(1) mpos(2) mpos(3:4)] );drawnow;';


% Update handles structure
guidata(hObject, handles);


[status dlsoutput] = system ('bash ./dcheck ');
if status ~=0
    ShowStatus('Xglom: Error DaRIS script failed checks.',handles);
end

% UIWAIT makes Xglom wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Xglom_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

child_handles = allchild(handles.figure1);
%delete(child_handles)
%delete(handles.figure1)



%% DaRIS ProjectID popup menu functions

function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%global cur
handles.output = hObject;
contents = cellstr(get(hObject,'String')); %returns popupmenu1 contents as cell array
if handles.debug
    disp(contents{get(hObject,'Value')}); %returns selected item from popupmenu1
end

ProjectID = regexp(contents{get(hObject,'Value')},'(\d+.\d+.\d+)','match');

% [status dlsoutput] = system (['bash ./dls  ' ProjectID])
% if status ==0
%     ShowStatus(dlsoutput,handles)
% else
%     ShowStatus('Xglom: Error you are not logged into DaRIS.',handles);
%     return
% end
handles.currentProject = char(ProjectID);
guidata(hObject, handles);

UpdateTable(handles);



% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
%UpdateProjects(handles)


%% PIPELINE button
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

ShowStatus('Running "Pipeline" ... ',handles);
Selection = handles.DatasetSelection;
table = get(handles.uitable2,'Data');

if isempty(Selection) || isempty(table) %|| length(Selection) > 3
    ShowStatus(' No dataset selected or table empty.',handles);
    return;
else
    
    
    curProj =handles.currentProject;
    if isempty(curProj)
        warndlg('No project selected. ', 'Xglom Warning', 'modal');
        return
    end
    
    %char(table{Selection(1),1})
    description = char(table{Selection(1),handles.TABLE_COL.Description});
    original_filtered_str = char(table{Selection(1),handles.TABLE_COL.OrigFilt});
    
    if strcmp(original_filtered_str,'P')
        
        if isempty(char(table{Selection(1)-1,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for depth image. ', 'Xglom Warning Dialog', 'modal');
            return;
        end
        DatasetID = [char(curProj) '.' char(table{Selection(1)-1,handles.TABLE_COL.CID})];
        [img info] = GetImage(DatasetID,'P',handles);
        
    elseif strcmp(original_filtered_str,'S')
        if isempty(char(table{Selection(1)-2,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for output stats. ', 'Xglom Warning', 'modal');
            return;
        end
        
        DatasetID = [char(curProj) '.' char(table{Selection(1)-2,handles.TABLE_COL.CID})];
        [img info] = GetImage(DatasetID,'S',handles);
    else
        if isempty(char(table{Selection(1),handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for dataset image. ', 'Xglom Warning', 'modal');
            return;
        end
        
        
        DatasetID = [char(curProj) '.' char(table{Selection(1),handles.TABLE_COL.CID})];
        
        switch handles.SelectionModality
            case 3
                % Call VM GUI
                FetchVM(DatasetID,handles);
                GlomViewer(fullfile(handles.LocalCache,DatasetID));
            case 2
                % CT pipeline
                [img info] = GetImage(DatasetID,'CT',handles);
                XglomPipeline('DARISID',DatasetID,'DATATYPE','CT', 'IMG',img)
            case 1
                % MR pipeline
                [img info] = GetImage(DatasetID,'MR',handles);
                XglomPipeline('DARISID',DatasetID,'DATATYPE','MR', 'IMG', img);
        end
        
        
        
    end
    
end


%wait(figure);close(figure0;
%
% telapsed = toc(tstart)
% ShowStatus('Running Masking: none ',handles)
% ShowStatus('Running Statistical tests ...',handles)
% addpath('/gpfs/M2Home/projects/Monash016/RatKidney/Agilent');
% [voxels diams labeledgloms] = DepthMeasures(depth);
% save(['.//Cache/' FullCID '/output_01.mat'],'voxels', 'diams', 'labeledgloms')
% telapsed = toc(tstart)
% figure; plot (cumsum(voxels'))
% ShowStatus('Pipeline complete for CID ',handles)
% CID

% Loop through selected images
%    end
%end
ShowStatus('Pipeline complete.',handles);


%% INSPECT button
% Selected line in dataset table is loaded for viewing purposes.
% Raw images are checked to see if they are in local cache or need to be
% retreived from DaRIS.  Depth images are currently stored as MAT files but
% could be stored in Daris in the future.
% Output images
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

ShowStatus('Running "Inpect" ... ',handles);
Selection = handles.DatasetSelection;
if isempty(Selection) %|| length(Selection) > 3
    ShowStatus(' No dataset selected or too many',handles);
    return;
else
    flag=0;
    table = get(handles.uitable2,'Data');
    curProj =handles.currentProject;
    %char(table{Selection(1),1})
    if isempty(curProj)
        warndlg('No project selected. ', 'Xglom Warning', 'modal');
        return;
    end
    
    
    description = char(table{Selection(1),handles.TABLE_COL.Description});
    
    %if ~isempty(strfind(description,'No processed'))
    if ~isempty(strfind(description,'depth'))
        if isempty(char(table{Selection(1)-1,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for depth image. ', 'Xglom Warning Dialog', 'modal');
            return;
        end
        
        DatasetID = [char(curProj) '.' char(table{Selection(1)-1,handles.TABLE_COL.CID})];
        img = GetImage(DatasetID,'P',handles);
        if numel(img)== 1
            flag=1;
        end
    elseif ~isempty(strfind(description,'stats'))
        
        if isempty(char(table{Selection(1)-2,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for output stats. ', 'Xglom Warning', 'modal');
            return;
        end
        
        DatasetID = [char(curProj) '.' char(table{Selection(1)-2,handles.TABLE_COL.CID})];
        if exist(fullfile(handles.LocalCache, DatasetID, 'output_01.mat'), 'file')
            load(fullfile(handles.LocalCache, DatasetID, 'output_01.mat'),'-regexp', '\<[^l].*\>')
            
            [img info] = GetImage(DatasetID,'S',handles);
            
            if numel(img)<2
                flag=1;
            end
            
            if exist('ThresholdRange','var') && exist('diams_range','var') && exist('GlomStats','var')
                PlotXGlomOutputDist(stored_hist,stored_diams,DatasetID,info.PixelDimensions(1),ThresholdRange,diams_range);%, GlomStats);
            else
                PlotXGlomOutputDist(stored_hist,stored_diams,DatasetID,info.PixelDimensions(1));
            end
        else
            errordlg(' Output statistics selection not available ','Xglom Error dialog')
            return
        end
    else
        if isempty(char(table{Selection(1),handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for raw image. ', 'Xglom Warning', 'modal');
            return;
        end
        
        
        DatasetID = [char(curProj) '.' char(table{Selection(1),handles.TABLE_COL.CID})];
        switch handles.SelectionModality
            case handles.VMmodality
                GetImage(DatasetID,'VM',handles);
            case handles.CTmodality
                [img info]= GetImage(DatasetID,'CT',handles);
            case handles.MRmodality
                [img info] = GetImage(DatasetID,'MR',handles);
        end
        
        
    end
    
    if handles.SelectionModality ~= handles.VMmodality
        if numel(img)< 2
            flag=1;
        end
        ShowStatus(['Inpect retreived image ' DatasetID ' size : ' num2str(size(img))],handles);
        %figure
        if flag == 0
            if max(img(:)) == 1
                imagesc3(img, 'clim', [0 1], 'colormap',flipud(gray),'DARISID', DatasetID);
            else
                imagesc3(img,'DARISID',DatasetID); %, 'clim', [min(img(:)) max(img(:))]);
            end
        end
        handles.Img = img;
    end
end


function [imgvol info] = GetImage(DarisID,tag, handles)
%% GetImage
% Searches local directory 'Cache' for dataset, otherwise gets it from
% DaRIS.

% Check for dataset in Cache
imgvol=[];
%[status lsoutput] =system(['ls ./Cache/' DarisID]);
%     if status ~= 0
%         ShowStatus(['Error no Cache directory for ' DarisID],handles)
%         return
%     end
currentFolder = pwd;
addpath([currentFolder '/plugins/dicom_toolbox_version_2e']);

if ~isempty(strfind(tag,'MR'))
    if ~isdir(fullfile(handles.LocalCache,DarisID)) && ~exist(fullfile(handles.LocalCache,DarisID,'0001.dcm'),'file')
        ShowStatus(['Getting dataset ' DarisID ' from DaRIS.'],handles);
        hMsg=msgbox(['Downloading MR dataset ' DarisID ' from DaRIS. Approximate download time 10 seconds.'],'Xglom Downloading . . . ');
%        delete(findobj(hMsg,'string','OK'));
%        delete(findobj(hMsg,'style','frame'));
%        mpos= get(hMsg,'position');set(hMsg,'position',[mpos(1)+36 mpos(2)-88 mpos(3:4)] );drawnow;
eval(handles.cleanmsgbox);
        [status lsoutput] =system(['bash ./dget -c ' DarisID '  -d ' handles.LocalCache]);
        delete(hMsg);
    else
        ShowStatus('Dataset in Cache. Loading in.',handles);
        
    end
    
    if ~exist(fullfile(handles.LocalCache,DarisID,'0001.dcm'),'file')
        ShowStatus('Error in Downloading dataset. No dataset folder',handles);
        return;
    else
        % Force group read/write to dicom in case sticky bit is not set
        system(['chmod 775 ' fullfile(handles.LocalCache,DarisID) ]);
    end
    
    if ~exist(fullfile(handles.LocalCache,DarisID,'0002.dcm'),'file')
        
        ShowStatus('Downloading dataset complete. Reading in.',handles);
        imgvol = dicom_read_volume(fullfile(handles.LocalCache,DarisID,'0001.dcm'));
        hReadInDialog=get(0,'CurrentFigure');close(hReadInDialog);
        pause(0.5);
        %system(['./dcmtools/bin/DCMDUMP ' fullfile(handles.LocalCache,DarisID,'0001.dcm') ]);
        ShowStatus('DICOM loaded.',handles);
        info = GetDICOMInfo(DarisID);
    else
        ShowStatus('Multi-file DICOM directory.',handles);
        imgvol = dicom_read_volume(fullfile(handles.LocalCache,DarisID));
        hReadInDialog=get(0,'CurrentFigure');close(hReadInDialog);
        pause(0.5);
        system(['./dcmtools/bin/DCMDUMP ' fullfile(handles.LocalCache,DarisID,'0001.dcm') ]);
        ShowStatus('DICOM loaded.',handles);
        info = GetDICOMInfo(DarisID);
    end
    
    imgvol = single(imgvol);
    imgvol = squeeze(imgvol);
    ShowStatus(['GetImage retreived image mean : ' num2str(mean(imgvol(:)))],handles);
    
elseif ~isempty(strfind(tag,'CT'))
    % Check for Dataset's directory or any contents
    if ~isdir(fullfile(handles.LocalCache,DarisID))
        
        aarcmd = sprintf('source ./dcheck; $MFCOMMAND asset.query :where "cid=''%s''" :action get-value :xpath content/type/@ext',DarisID);
        [status aaroutput] =system(aarcmd);
        
        if ~status &&  strfind(aaroutput,'aar')
            % CT Tiff format
            status = FetchCTtiff(DarisID,handles);
        else
            % CT DICOM format
            ShowStatus(['Getting dataset ' DarisID ' from DaRIS.'],handles);
            hMsg=msgbox(['Downloading CT dataset ' DarisID ' from DaRIS. Approximate download time 1 minute.'],'Xglom Downloading . . . ');
            eval(handles.cleanmsgbox);
            [status lsoutput] =system(['bash ./dget -c ' DarisID '  -d ' fullfile(handles.LocalCache)]);
            delete(hMsg);
        end
        
        
        if status
            errordlg('Xglom:  GetImage dget failed.', 'Xglom Error Dialog', 'modal');
            return;
            
        end
        
        
    end
    
    if ~isdir(fullfile(handles.LocalCache,DarisID))
        errordlg('Getting CT image failed.', 'Xglom Error Dialog', 'modal');
    elseif exist(fullfile(handles.LocalCache, DarisID, '0001.dcm'),'file')
        % CT DICOM format
        % read directory
        [imgvol info] = GetCTDicomImage(fullfile(handles.LocalCache, DarisID));
        
    elseif exist(fullfile(handles.LocalCache, DarisID,'0001_01_01', '0001.tif'),'file')
        % CT Tiff format
        
        % read directory
        [imgvol info] = GetCTtiffImage(fullfile(handles.LocalCache, DarisID));
        
    else
        errordlg('Getting CT image failed.', 'Xglom Error Dialog', 'modal');
    end
    
elseif ~isempty(strfind(tag,'VM'))
    
    FetchVM(DarisID,handles);
    
elseif ~isempty(strfind(tag,'P')) % processed data from pipeline
    ShowStatus(['Getting processed depth image ' DarisID ' from local directory Cache .'],handles);
    
    if exist(fullfile(handles.LocalCache,DarisID, 'depth_mask_01.mat'),'file')
        ShowStatus('Processed depth image in Cache. Loading in.',handles)
        load(fullfile(handles.LocalCache,DarisID, 'depth_mask_01.mat')); imgvol= depth;
        ShowStatus(['Processed depth image size: ' num2str(size(imgvol))],handles);
        imgvol = single(imgvol);
        imgvol = squeeze(imgvol);
    else
        ShowStatus('Error in loading processed images.',handles);
        return;
    end
    
elseif  ~isempty(strfind(tag,'S')) % Statistics/ output data of pipeline
    ShowStatus(['Getting output stats of ' DarisID ' from local directory Cache.'],handles);
    
    if exist(fullfile(handles.LocalCache,DarisID, 'output_01.mat'),'file')
        
        ShowStatus('Processed output in Cache. Loading in.',handles);
        load(fullfile(handles.LocalCache,DarisID, 'output_01.mat'), 'labeledgloms');
        imgvol=labeledgloms>0;
        if exist(fullfile(handles.LocalCache,DarisID,'info.txt'),'file')
            data_cell_string = fileread(fullfile(handles.LocalCache,DarisID,'info.txt'));
            data_cell_string = regexp(data_cell_string,'\s+','split');
            
            for i=1:length(data_cell_string)
                if ~isempty(strfind(data_cell_string{i},'NZ='))
                    info.NumSlides =  str2double(data_cell_string{i}(4:end));
                end
                if ~isempty(strfind(data_cell_string{i},'DX='))
                    info.PixelDimensions =  str2double(data_cell_string{i}(4:end));
                end
                if ~isempty(strfind(data_cell_string{i},'DZ='))
                    info.SliceSeperation =  str2double(data_cell_string{i}(4:end));
                end
                if ~isempty(strfind(data_cell_string{i},'TX='))
                    info.XTiles =  str2double(data_cell_string{i}(4:end));
                end
                if ~isempty(strfind(data_cell_string{i},'TY='))
                    info.YTiles =  str2double(data_cell_string{i}(4:end));
                end
            end
        else
            info = GetDICOMInfo(DarisID);
        end
    else
        ShowStatus('Error in loading output stats.',handles);
        return; %1.;
    end
    
end


function status = FetchCTtiff(DarisID,handles)
ShowStatus(['Fetching CT tiff dataset ' DarisID '.'],handles);
% Check for Dataset's directory or any contents
status=0;
if  ~isdir(fullfile(handles.LocalCache,DarisID))
    ShowStatus(['Getting CT dataset ' DarisID ' from DaRIS.'],handles);
    
    ShowStatus('Check that it is stored as an AAR file on DaRIS',handles)
    
    aarcmd = sprintf('source ./dcheck; $MFCOMMAND asset.query :where "cid=''%s''" :action get-value :xpath content/type/@ext',DarisID);
    [status aaroutput] =system(aarcmd);
    
    if ~status &&  strfind(aaroutput,'aar')
        tmp_regexp = regexp(aaroutput,':asset -id "(\d{4,8})" -version "\d*"', 'tokens');
        if ~isempty(tmp_regexp)
            MediaFluxID = char( tmp_regexp{1} );
        else
            errordlg ('Unable to get download CT.','Xglom Error Dialog', 'modal');
            return;
        end
        
        %% Download the VM using java backend to DaRIS
        hMsg=msgbox(['Downloading CT dataset ' DarisID ' from DaRIS. Approximate download time 5 minutes. To terminate download go to the terminal window and press Ctrl-c.'],'Xglom Fetch CT tiffImage: Downloading . . . ');
        eval(handles.cleanmsgbox);        
        dwncmd = sprintf('time ( source ./dcheck;$MFCOMMAND asset.get :id "%s" :out file:"%s".aar  )', MediaFluxID,fullfile(handles.LocalCache,DarisID));
        [status lsoutput] =system(dwncmd);
        delete(hMsg);
        msgbox('FetchCTtiff: Download complete. Click OK to continue.','Xglom Downloading Finished ','modal');
        if status
            errordlg('FetchCTtiff: download failed. Click OK to continue.', 'Xglom Error Dialog', 'modal');
            return;
        else
            
            %% Unpacking AAR
            hMsg=msgbox(['Downloading Complete. Unpacking CT dataset ' DarisID '. Approximate unpack time 3-4 minutes.'],'Xglom Fetch CT Image: Unpacking . . . ');
            eval(handles.cleanmsgbox);
            [status unpackoutput] = system(['mkdir -p ' fullfile(handles.LocalCache, DarisID) ]);
            [status unpackoutput] = system(['time java -jar "./aar.jar" -extract ' fullfile(handles.LocalCache,DarisID) '.aar  ' fullfile(handles.LocalCache,DarisID) ]);
            [status unpackoutput] = system(['find ' fullfile(handles.LocalCache,DarisID) ' -type d -exec chmod 775 {} \; ']);
            delete(hMsg);
            
            ShowStatus('Unpacking Complete. ', 'Xglom Fetch CT tiff Image',handles);
        end
    else
        errordlg ('FetchCT: Unable to get download VM.  Dataset must have ''aar'' extension.','Xglom Error Dialog', 'modal')
        return
    end
    
    [status lsoutput] = system(['ls ' fullfile(handles.LocalCache,DarisID) '/*']);
    if ~isempty(strfind(lsoutput,'No such file or directory'))
        errordlg('Getting CT image failed.', 'Xglom Error Dialog', 'modal');
        return
    end
else
    ShowStatus(['Getting CT dataset ' DarisID ' already in Cache.'],handles);
end




function FetchVM(DarisID,handles)
ShowStatus(['Fetching VM dataset ' DarisID '.'],handles);
% Check for Dataset's directory or any contents

if  ~isdir(fullfile(handles.LocalCache,DarisID))
    ShowStatus(['Getting VM dataset ' DarisID ' from DaRIS.'],handles);
    
    ShowStatus('Check that it is stored as an AAR file on DaRIS',handles);
    
    aarcmd = sprintf('source ./dcheck; $MFCOMMAND asset.query :where "cid=''%s''" :action get-value :xpath content/type/@ext',DarisID);
    [status aaroutput] =system(aarcmd);
    
    if ~status &&  strfind(aaroutput,'aar')
        tmp_regexp = regexp(aaroutput,':asset -id "(\d{4,8})" -version "\d*"', 'tokens');
        if ~isempty(tmp_regexp)
            MediaFluxID = char( tmp_regexp{1} );
        else
            error ('Unable to get download VM.');
        end
        
        %% Download the VM using java backend to DaRIS
        hMsg=msgbox(['Downloading VM dataset ' DarisID ' from DaRIS. Approximate download time 20 minutes. To terminate download go to the terminal window and press Ctrl-c.'],'Xglom Fetch VM Image: Downloading . . . ');
        eval(handles.cleanmsgbox);
        dwncmd = sprintf('source ./dcheck;$MFCOMMAND asset.get :id "%s" :out file:"%s".aar', MediaFluxID,fullfile(handles.LocalCache,DarisID));
        [status lsoutput] =system(dwncmd);
        delete(hMsg);
        msgbox('FetchVM: Download complete','Xglom Downloading Finished ','modal');
        if status
            errordlg('FetchVM: download failed.', 'Xglom Error Dialog', 'modal');
            return;
        else
            
            %% Unpacking AAR
            hMsg=msgbox(['Downloading Complete. Unpacking VM dataset ' DarisID '. Approximate unpack time 2 minutes.'],'Xglom Fetch VM Image: Unpacking . . . ');
            eval(handles.cleanmsgbox);
            [status unpackoutput] = system(['mkdir -p ' fullfile(handles.LocalCache,DarisID) ]);
            [status unpackoutput] = system(['java -jar "./aar.jar" -extract ' fullfile(handles.LocalCache,DarisID) '.aar  ' fullfile(handles.LocalCache,DarisID) ]);
            [status unpackoutput] = system(['find ' fullfile(handles.LocalCache,DarisID) ' -type d -exec chmod 775 {} \; ']);
            delete(hMsg);
            
            msgbox(['Unpacking Complete. You can run GlomViewer with dataset ' DarisID '. click OK to continue.'], 'Xglom Fetch VM Image','modal');
        end
    else
        errordlg ('FetchVM: Unable to get download VM.  Dataset must have ''aar'' extension.','Xglom Error Dialog', 'modal');
        
    end
    
    [status lsoutput] = system(['ls ' fullfile(handles.LocalCache,DarisID) '/*']);
    if ~isempty(strfind(lsoutput,'No such file or directory'));
        errordlg('Getting VM image failed.', 'Xglom Error Dialog', 'modal');
    end
    
end



function pushbutton3_Callback(hObject, eventdata, handles)
%% Logon button
% Call the DaRIS dialog then update project popup menu.
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ShowStatus('Running DaRIS logon  ...',handles);
hLogon = DarisDialog;
uiwait(gcf);
UpdateProjects(handles);
ShowStatus(' DaRIS logon complete.',handles);


%% CLOSE button
% Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ShowStatus('Closing KidneyProject Application',handles);
close(handles.figure1);

%% Dataset select function
% --- Executes when entered data in editable cell(s) in uitable2.
function uitable2_CellEditCallback(hObject, eventdata, handles)
% hObject    handle to uitable2 (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) edited
%	PreviousData: previous data for the cell(s) edited
%	EditData: string(s) entered by the user
%	NewData: EditData or its converted form set on the Data property. Empty if Data was not changed
%	Error: error string when failed to convert EditData to appropriate value for Data
% handles    structure with handles and user data (see GUIDATA)
if handles.debug
    display eventdata;
end
selection = eventdata.Indices;
table = get(handles.uitable2,'Data');
table{selection(1),1} = ~table{selection(1),1};   % Selection toggle


% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array
%        contents{get(hObject,'Value')} returns selected it from popupmenu2


% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes when selected cell(s) is changed in uitable2.
function uitable2_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to uitable2 (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) currently selecteds
% handles    structure with handles and user data (see GUIDATA)

handles.Img = [];
handles.DatasetSelection = eventdata.Indices;
if ~isempty(handles.DatasetSelection)
    table = get(handles.uitable2,'Data');
    if ~isempty(table)
        description = table{handles.DatasetSelection(1),3};
        if ~isempty(strfind(description,'MR'))
            handles.SelectionModality=1;
        elseif ~isempty(strfind(description,'CT'))
            handles.SelectionModality=2;
        elseif ~isempty(strfind(description,'VM'))
            handles.SelectionModality=3;
        else
            handles.SelectionModality=0;
        end
    else
        handles.SelectionModality=0;
    end
else
    handles.SelectionModality=0;
end

ShowStatus(['Modality ' num2str(handles.SelectionModality)],handles)

if handles.SelectionModality == 3
    set (handles.pushbutton1, 'string','Run GlomViewer');
    set (handles.pushbutton2, 'string','Fetch VM dataset');
    set (handles.pushbutton2, 'enable','on');
    
else
    set (handles.pushbutton1, 'string','Run Pipeline');
    set (handles.pushbutton2, 'string','Inspect');
    set (handles.pushbutton2, 'enable','on');
    
end

guidata(hObject,handles)
%table = get(handles.uitable2,'Data')
%table{selection(1),1} = ~table{selection(1),1};   % Selection toggle
% t=get(gcf,'SelectionType');
%
% switch t
%   case 'normal' % left button was clicked
%       % code desired when left button was used
%   otherwise % middle, right, or double click
%       % code desired when anything but left button was used
% end


%% Clean dataset table
function datastrings = FilterDatasets(datastrings,varg)
% Filter cell array 'datastrings' with expressions in 'varg'
if ~isempty(varg)
    if ischar(varg)
        datastrings = regexp(datastrings,['.*' varg '.*'],'match');
        ShowStatus(['Filtering ' varg ' from datasets.' ],handles)
    else iscell(varg)
        for ii = 1:length(varg)
            ShowStatus(['Filtering ' varg{ii} ' from datasets.' ],handles)
            datastrings = regexp(datastrings,['.*' varg{ii} '.*'],'match');
            %% Clean list
            datastrings(cellfun(@isempty, datastrings))=[];
        end
    end
end

% Remove empty elements
datastrings(cellfun(@isempty, datastrings))=[];

%% Filter out modalities using checkboxes
function outstr = getCheckboxes(handles)
outstr = '';
if get(handles.checkbox1,'Value')
    outstr = horzcat(outstr,'MR ');
end
if get(handles.checkbox2,'Value')
    outstr = horzcat(outstr,'CT ');
end
if get(handles.checkbox3,'Value')
    outstr = horzcat(outstr,'OM ');
end
if get(handles.checkbox4,'Value')
    outstr = horzcat(outstr,'Processed ');
end
if get(handles.checkbox6,'Value')
    outstr = horzcat(outstr,'Raw ');
end


%% Update the Project ID popup menu
function [count] = UpdateProjects(handles)
ShowStatus('Updating Project popup menu ...',handles);
hMsg= msgbox('Calling the DaRIS server to see what projects you have access to.  Depending on networking issues, this may take some time.','Communicating with DaRIS server');
eval(handles.cleanmsgbox);
[status dlsoutput] = system ('bash ./dls ');
delete(hMsg)
%set(handles.outputbox,'String',[output dlsoutput]);
hMsg = msgbox(' Updating project list. Please wait.','Xglom -- Updating Projects');
eval(handles.cleanmsgbox);
ount=0;
if ~status
    listelem =regexp(dlsoutput, '\n', 'split');
    listelem(cellfun(@isempty, listelem))=[];
    %set(handles.listbox1,'String',listelem)
    elems = regexp(listelem,'(\d+.\d+.\d+).*','match');
    PIDs{length(elems)}=[];   % preallocate memory for project IDs
    
    switch length(elems)
        case 0
            count=0;
            
        case 1
            PIDs{1}=cellstr(elems{1});
            count=1;
        otherwise
            
            PIDs{1}=cellstr(elems{1});
            count=2;
            for ii = 2:length(elems)
                if ~isempty(elems{ii}) && iscell(elems{ii})
                    PIDs{1}(count)=cellstr(elems{ii});
                    count=count+1;
                end
            end
    end
    PIDs(cellfun(@isempty, PIDs))=[];
    if isempty(PIDs)
        PIDs={'No Projects'};
        curProj='';
    else
        curProj=PIDs{1}(1);
    end
    % disp(PIDs{1});
    set(handles.popupmenu1,'String',PIDs{1});
    ShowStatus('Updating DaRIS projects ...       done.',handles);
    
else
    ShowStatus('Updating DaRIS projects ... FAILED.',handles);
end
delete(hMsg)


%% Update the dataset table
function UpdateTable(handles,varg)

global table
ShowStatus('Updating Tables ...',handles);
hMsgTable = msgbox(' Updating dataset table. Please wait.','Xglom -- Updating Table');
eval(handles.cleanmsgboxtable);

handles.output = handles.uitable2;
curProj= handles.currentProject;
handles.Img=[];
table = get(handles.uitable2,'Data');
clear table;

if isempty(handles.DatasetListing)
    % Call ./dls using the '-p' argument to test filtered or original
    % image
    hMsg = msgbox('Calling the DaRIS server to see what projects you have access to.  Depending on networking issues, this may take some time.','Communicating with DaRIS server');
    eval(handles.cleanmsgbox);

    if isempty(curProj)
        [status dlsoutput] = system ('bash ./dls -p -r 0 1008.2.18'); %#ok<*ASGLU>
    else
        [status dlsoutput] = system (['bash ./dls -p -r 0 ' curProj ]);
    end
    delete(hMsg)
    %set(handles.outputbox,'String',[output dlsoutput]);
    listelem =regexp(dlsoutput, '\n', 'split');
    listelem= regexp(listelem,'.*dataset.*','match'); % Filtering elements with sting 'dataset'
    listelem(cellfun(@isempty, listelem))=[];  % Cleaning list
    handles.DatasetListing= listelem;
else
    listelem = handles.DatasetListing;
end

if handles.debug
    disp(listelem);
end
if isempty(listelem)
    table = get(handles.uitable2,'Data');
    clear table;
    ShowStatus('No datasets in project or DaRIS unavailable.',handles);
    table{1,1}='No datasets in project';
    set(handles.uitable2,'Data',table);
    return
end


show_processed = 0;         % this variable flags whether dataset should
% look for processed data or not


count=1;
item_path='';
num_datasets=length(listelem);

% Pre-allocate memory for table
if handles.ProcessedImageCheckbox
    table{num_datasets,9}=[];
else
    table{(num_datasets*3),9} = [];
end

for ii=1:length(listelem)
    if handles.debug
        disp(listelem{ii});
    end
    if ~isempty(strfind(listelem{ii},'dataset')) ; % double checking filter
        
        ShowStatus(['Dataset at line number ' num2str(ii)],handles);
        
        sline = regexp(listelem{ii},'\s+','split');
        original_or_filtered = str2double(sline{1}(handles.DLS_OrigFilt_COL));
        if handles.debug
            ShowStatus(['   Dataset O/F flag is ' num2str(original_or_filtered)],handles);
        end
        
        % is the O/F checkbox on and is this dataset an original image
        if ((handles.OriginalImageCheckbox == 1) && (original_or_filtered == 0))
            
            ShowStatus(['   Original Image, Modality: ' char(sline{1}(handles.DLS_MODALITY_COL))],handles);
            
            switch char(sline{1}(handles.DLS_MODALITY_COL))
                case 'MR'
                    if handles.MRModalityCheckbox
                        
                        table = FormatDatasetLine(table,count,sline,original_or_filtered,handles);
                        count=count+1;
                        show_processed = 1;
                    end
                case 'CT'
                    if handles.CTModalityCheckbox
                        
                        table = FormatDatasetLine(table,count,sline,original_or_filtered,handles);
                        count=count+1;
                        show_processed = 1;
                    end
                case 'OT' % VM
                    if  handles.VMModalityCheckbox
                        
                        table = FormatDatasetLine(table,count,sline,original_or_filtered,handles);
                        count=count+1;
                        show_processed = 0;
                    end
            end
            
            
        elseif ((handles.FilteredImageCheckbox == 1) && (original_or_filtered ==1))
            
            
            if (handles.MRModalityCheckbox == 1)
                ShowStatus(['   Filtered MR Modality: ' sline{1}(handles.DLS_CIDCOL)],handles);
                % Sort into proper columns
                daris_num = regexp(sline{1}(handles.DLS_CIDCOL),'\.','split');
                item_path = [char(daris_num{1}(4)) '.' char(daris_num{1}(5)) '.' char(daris_num{1}(6)) '.' char(daris_num{1}(7))];
                table{count,handles.TABLE_COL.CID} = item_path;
                table{count,handles.TABLE_COL.SIZE} = printfilesize(str2double(char(sline{1}(handles.DLS_SIZE_COL)))); %Size
                descr = char(sline{1}(handles.DLS_MODALITY_COL)); % get modality
                length(sline{1});
                if length(sline{1}) >= handles.DLS_Description_COL
                    for jj = handles.DLS_Description_COL:length(sline{1})
                        descr = horzcat(descr,' ', char(sline{1}(jj)));
                    end
                    if handles.debug
                        ShowStatus(['   Dataset description: ' descr],handles);
                    end
                    table{count,handles.TABLE_COL.Description} = descr;  %Description
                    
                end
                table{count,handles.TABLE_COL.OrigFilt}='F';
                table{count,handles.TABLE_COL.DATE} = char(sline{1}(handles.DLS_DATE_COL));  %Date
                table{count,handles.TABLE_COL.TIME} = char(sline{1}(handles.DLS_TIME_COL));  %Time
                %table{count,6} = char(sline{1}(handles.DLS_CIDCOL)); %Full CID
                %table{count,:}
                count=count+1;
                show_processed=1;
            else
                ShowStatus('   MR modality checkbox not selected.',handles);
                
            end
        end
        if (handles.ProcessedImageCheckbox == 1) && (show_processed == 1)
            if handles.debug
                ShowStatus('Searching for processed images and output data in cache, then adding extra line in table.',handles);
            end
            curProj = handles.currentProject;
            if ~isempty(curProj)
                DarisID = char(sline{1}(handles.DLS_CIDCOL));
                if isdir(fullfile(handles.LocalCache, DarisID))
                    if handles.debug
                        ShowStatus([' Found directory for image ' DarisID],handles);
                    end
                    
                    if exist(fullfile(handles.LocalCache,DarisID,'depth_mask_01.mat'),'file')
                        %                        table{count,:} = FormatExtraDatasetLine(lsoutput,'Processed data: depth , mask ', handles, table{count-1,:});
                        table{count,handles.TABLE_COL.CID} = '';
                        table{count,handles.TABLE_COL.OrigFilt}='D';
                        table{count,handles.TABLE_COL.Description} = 'Processed data: depth , mask ' ;% lsoutput];
                        [status lsoutput] = system (['ls -l Cache/' DarisID '/depth_mask*.mat']);
                        lsoutput = regexp(lsoutput,'\s+','split');
                        
                        table{count,handles.TABLE_COL.SIZE} = printfilesize(str2double(char(lsoutput{5}))); %Size
                        table{count,handles.TABLE_COL.DATE} = sprintf('%s-%s-%s',char(lsoutput{7}),char(lsoutput{6})); %Date
                        table{count,handles.TABLE_COL.TIME} = char(lsoutput{8}); % Time
                        
                        count=count+1;
                        
                        %
                        if exist(fullfile(handles.LocalCache,DarisID,'output_01.mat'),'file')
                            %size(table{count-1,:})
                            %   table{count,:} = FormatExtraDatasetLine(lsoutput,'Output: stats + histograms  ', handles);
                            table{count,handles.TABLE_COL.CID} = '';
                            table{count,handles.TABLE_COL.OrigFilt}='S';
                            table{count,handles.TABLE_COL.Description} ='Output: stats + histograms  ' ;% lsoutput];
                            [status lsoutput] = system (['ls -l ./Cache/' DarisID '/output*.mat']);
                            lsoutput = regexp(lsoutput,'\s+','split');
                            table{count,handles.TABLE_COL.SIZE} = printfilesize(str2double(char(lsoutput{5}))); %Size
                            table{count,handles.TABLE_COL.DATE} = sprintf('%s-%s-%s',char(lsoutput{7}),char(lsoutput{6})); %Date
                            table{count,handles.TABLE_COL.TIME} = char(lsoutput{8}); % Time
                            
                            count=count+1;
                        end
                    else
                        if handles.debug
                            ShowStatus(['Directory found but no processed image ' item_path],handles);
                        end
                        table{count,handles.TABLE_COL.Description} = 'No processed data';
                        count=count+1;
                    end
                else
                    if handles.debug
                        ShowStatus([' No directory for image ' item_path],handles);
                    end
                    table{count,handles.TABLE_COL.Description} = 'No processed data';
                    count=count+1;
                    %
                end
                %
            else
                table{count,handles.TABLE_COL.Description} = 'No processed or output data';
                count=count+1;
            end
            show_processed = 0;
            %             %             %Reset
            %             %
            %             %             item_path='';
        end
        
    end
end
table(all(cellfun(@isempty, table),2),: )=[];
set(handles.uitable2,'Data',table);
ShowStatus('Updating table done.',handles);
delete(hMsgTable);
%guidata(hObject,handles)

%
% Printfilesize size (in bytes) to human readable string
% Adapted from http://stackoverflow.com/questions/3898840/converting-a-number-of-bytes-into-a-file-size-in-c
function output = printfilesize(filesize)
BSIZES = { 'B', 'kB', 'MB', 'GB' };
div = 1;rem = 0;
while (filesize >= 1024 && div < numel(BSIZES))
    rem = mod(filesize, 1024);
    div=div+1;
    filesize = filesize / 1024;
end
output = sprintf('%.1f %s', single(filesize) + single(rem) / 1024.0, char(BSIZES{div}));

function table = FormatDatasetLine(table,count,sline,of_flag,handles)
% FormatDatasetLine parses the dls dataset string
%
% of_flag:  string containing original ('O') or filtered ('F') flag
daris_num = regexp(sline{1}(handles.DLS_CIDCOL),'\.','split');
subjstudyID = [char(daris_num{1}(4)) '.' char(daris_num{1}(5)) '.' char(daris_num{1}(6)) '.' char(daris_num{1}(7))];
table{count,handles.TABLE_COL.CID} = subjstudyID;
table{count,handles.TABLE_COL.SIZE} = printfilesize(str2double(char(sline{1}(handles.DLS_SIZE_COL)))); %num2str(int32(str2double(char(sline{1}(handles.DLS_SIZE_COL)))/(1024*1024)),'%d'); %size in GB
descr = char(sline{1}(handles.DLS_MODALITY_COL)); % get modality
if ~isempty(strfind(descr,'OT'))
    descr = 'VM';
end
length(sline{1});
if length(sline{1}) >= handles.DLS_Description_COL
    for jj = handles.DLS_Description_COL:length(sline{1})
        descr = horzcat(descr,' ', char(sline{1}(jj)));
    end
    if handles.debug
        ShowStatus(descr,handles)
    end
    table{count,handles.TABLE_COL.Description} = descr;  %Description
end
if of_flag == 0
    
    table{count,handles.TABLE_COL.OrigFilt}='O';
else
    table{count,handles.TABLE_COL.OrigFilt}='F';
end
table{count,handles.TABLE_COL.DATE} = char(sline{1}(handles.DLS_DATE_COL));  %Date
table{count,handles.TABLE_COL.TIME} = char(sline{1}(handles.DLS_TIME_COL));  %Time


% the order of the tablerow structure is dependent on the dataset table format
% any changes to the table format will have to be mimicked here.
% tablerow = { subjstudyID, ...
%  of_flag, ...
%  descr, ...
%  num2str(int32(str2double(char(sline{1}(handles.DLS_SIZE_COL)))/(1024.)),'%d'), ...
%   char(sline{1}(handles.DLS_DATE_COL)), ...
%   char(sline{1}(handles.DLS_TIME_COL))};

function tablerow =  FormatExtraDatasetLine(lsoutput,description,handles)
lsoutput = regexp(lsoutput,'\s+','split');

% tablerow{1,handles.TABLE_COL.CID} = '';
% tablerow{1,handles.TABLE_COL.OrigFilt}='D';
% tablerow{1,handles.TABLE_COL.Description} = description ;% lsoutput];
% lsoutput = regexp(lsoutput,'\s+','split');
% tablerow{1,handles.TABLE_COL.SIZE} = char(lsoutput{5}); %Size
% tablerow{1,handles.TABLE_COL.DATE} = sprintf('%s-%s-%s',char(lsoutput{7}),char(lsoutput{6})); %Date
% tablerow{1,handles.TABLE_COL.TIME} = char(lsoutput{8}); % Time
tablerow = {'', ...
    'D', ...
    description,...
    char(lsoutput{5}),...
    sprintf('%s-%s-%s',char(lsoutput{7}),char(lsoutput{6})),...
    char(lsoutput{8})};



% --- Executes on selection change in popupmenu3.
function popupmenu3_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu3 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu3



% --- Executes during object creation, after setting all properties.
function popupmenu3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in togglebutton1.
function togglebutton1_Callback(hObject, eventdata, handles)
% hObject    handle to togglebutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDAsgetCheckTA)

% Hint: get(hObject,'Value') returns toggle state of togglebutton1


% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles) %#ok<*INUSL>
% hObject    handle to checkbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox1
handles.MRModalityCheckbox=get(hObject,'Value'); % returns toggle state of checkbox1
UpdateTable(handles);
guidata(hObject, handles);

% --- Executes on button press in checkbox2.
function checkbox2_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox2
handles.CTModalityCheckbox=get(hObject,'Value'); % returns toggle state of checkbox1
UpdateTable(handles);
guidata(hObject, handles);

% --- Executes on button press in checkbox3.
function checkbox3_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox3
handles.VMModalityCheckbox=get(hObject,'Value'); % returns toggle state of checkbox7
UpdateTable(handles);
guidata(hObject, handles);

%% Logon -- menu-bar item
function LogonMenu_Callback(hObject, eventdata, handles)
% hObject    handle to LogonMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ShowStatus('Running DaRIS logon  ...',handles)
hLogon=DarisDialog;
uiwait(hLogon)
hMsg = msgbox('You are logged into DaRIS. Updating Projects ...','Xglom initialising');
eval(handles.cleanmsgbox);
numProj=UpdateProjects(handles);
delete(hMsg)
% if numProj == 1
%    set(handles.popupmenu1,'Value',1)
%    guidata(hObject, handles);
%    UpdateTable(handles);
% end

%% Update ProjectID popupmenu -- menu-bar item
function UpdateProjMenu_Callback(hObject, eventdata, handles)
% hObject    handle to UpdateProjMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.DatasetListing=[];
numProj=UpdateProjects(handles);

if numProj == 1
    UpdateTable(handles);
end
guidata(hObject, handles);

%% Update dataset table -- menu-bar item
function UpdateTablesMenu_Callback(hObject, eventdata, handles)
% hObject    handle to UpdateTablesMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.Img=[];
handles.DatasetListing=[];
UpdateTable(handles);
guidata(hObject, handles);


function GetDataFromDaRIS(CID)
if ischar(CID) && ~isempty(CID)
    ShowStatus('CID is empty or not a string',handles)
    return
end
hMsg = msgbox([' Getting dataset ' CID ],'Xglom <-> DaRIS');
eval(handles.cleanmsgbox);
[status output] = system (['bash ./dget -c ' CID ' -d ' fullfile(handles.LocalCache)]);
delete(hMsg)
if status==0
    ShowStatus('Dataset retreived',handles)
    
else
    ShowStatus(['Unable to retreive image ' CID],handles)
    %table{count,2} = 'No processed data';
end


% --- Executes on button press in checkbox4.
function checkbox4_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox4
handles.ProcessedImageCheckbox=get(hObject,'Value');
ShowStatus(['Processed checkbox: ' num2str(handles.ProcessedImageCheckbox)] ,handles);
UpdateTable(handles);
guidata(hObject, handles);


% --- Executes on button press in checkbox6.
function checkbox6_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox6
handles.OriginalImageCheckbox=get(hObject,'Value');
UpdateTable(handles);
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function text5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to text5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

set(hObject,'String', 'Xglom  Kidney Analysis Toolkit');
guidata(hObject, handles);


% --- Executes on button press in checkbox7.
function checkbox7_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.FilteredImageCheckbox=get(hObject,'Value'); % returns toggle state of checkbox7
UpdateTable(handles);
guidata(hObject, handles);

% --------------------------------------------------------------------
function HelpMenu_Callback(hObject, eventdata, handles)
% hObject    handle to HelpMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --------------------------------------------------------------------
function AboutMenu_Callback(hObject, eventdata, handles)
% hObject    handle to AboutMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

helpdlg({sprintf('Xglom -- The Glomeruli Explorer -- (version %s)',handles.Xglom_version),...
'Xglom is a multi-modal kidney image analysis application for MR, CT and VM images for identification and quantification of glomeruli in kidneys.  The application was developed by Michael Eager at Monash Biomedical Imaging for Prof. John Bertram''s Lab in the Department of Anatomy and Developmental Biology, Monash University.  Funding for this project was through the Australian National Data Service (ands.org.au).',...
'',...
'Home page:','https://sites.google.com/a/monash.edu/kidney-image-analysis/',...
'Source code: https://code.google.com/p/xglom/',...
'Licence: GPL version 3'},'Xglom kidney image analysis toolkit');

% --------------------------------------------------------------------
function ModifyMenu_Callback(hObject, eventdata, handles)
% hObject    handle to ModifyMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function FilteredMenu_Callback(hObject, eventdata, handles)
% hObject    handle to FilteredMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ShowStatus('Running "Set Filtered ..." menu item ',handles)
Selection = handles.DatasetSelection;
if isempty(Selection) %|| length(Selection) > 3
    ShowStatus('No dataset selected or too many',handles);
    return;
else
    
    table = get(handles.uitable2,'Data');
    curProj =handles.currentProject;
    if ~isempty(char(table{Selection(1),handles.TABLE_COL.CID}));
        DatasetID = [char(curProj) '.' char(table{Selection(1),handles.TABLE_COL.CID})];
        hMsg = msgbox(' Communicating with DaRIS server to manipulate metadata.','Xglom <-> DaRIS');
eval(handles.cleanmsgbox);
        [status sys_output] = system(['bash ./dprocessed -c ' DatasetID ' -p 1']);
        delete(hMsg);
        if status ~= 0
            ShowStatus('Error in calling dprocessed.',handles);
        end
    else
        ShowStatus('FilteredMenu: no dataset ID in seclected row.',handles);
    end
end

UpdateTable(handles);


% --------------------------------------------------------------------
function UnsetFilteredMenu_Callback(hObject, eventdata, handles)
% hObject    handle to UnsetFilteredMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ShowStatus('Running "Unset Filtered ..." menu item ',handles)
Selection = handles.DatasetSelection;
if isempty(Selection) %|| length(Selection) > 3
    ShowStatus('No dataset selected or too many',handles);
    return
else
    
    table = get(handles.uitable2,'Data');
    curProj =handles.currentProject;
    if ~isempty(char(table{Selection(1),handles.TABLE_COL.CID}))
        DatasetID = [char(curProj) '.' char(table{Selection(1),handles.TABLE_COL.CID})];
        [status sys_output] = system(['bash ./dprocessed -c ' DatasetID ' -p 0']);
        if status ~= 0
            ShowStatus('Error in calling dprocessed.',handles);
        end
    else
        ShowStatus('UnsetFilteredMenu: no dataset ID in seclected row.',handles);
    end
end

UpdateTable(handles);



% --------------------------------------------------------------------
function DeleteDatasetMenu_Callback(hObject, eventdata, handles)
% hObject    handle to DeleteDatasetMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

ShowStatus('Running "Delete Dataset ..." menu item ',handles);
Selection = handles.DatasetSelection;
if isempty(Selection) %|| length(Selection) > 3
    ShowStatus('No dataset selected or too many',handles);
    return
else
    
    table = get(handles.uitable2,'Data');
    curProj =handles.currentProject;
    if ~isempty(char(table{Selection(1),handles.TABLE_COL.CID}))
        DatasetID = [char(curProj) '.' char(table{Selection(1),handles.TABLE_COL.CID})];
        [status sys_output] = system(['bash ./ddestroy -c ' DatasetID ]); %#ok<*NASGU>
        if status ~= 0
            ShowStatus('Error in calling ddestroy.',handles);
        end
    else
        ShowStatus('DeleteDatasetMenu: no dataset ID in seclected row.',handles);
    end
end

UpdateTable(handles);


% --------------------------------------------------------------------
function OpenDaris_Callback(hObject, eventdata, handles) %#ok<*INUSD,*DEFNU>
% hObject    handle to OpenDaris (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% open https://mf-erc.its.monash.edu.au:8443/daris/DaRIS.html
% standard MATLAB call to open url does not work on MASSIVE

system('bash -l -c "module load firefox; nohup firefox https://mf-erc.its.monash.edu.au:8443/daris/DaRIS.html &" - 2>&1 /dev/null');


% --------------------------------------------------------------------
function OpenSamba_Callback(hObject, eventdata, handles)
% hObject    handle to OpenSamba (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
username = GetDARISusername();
system (['konqueror smb://MONASH%5C' username '@lsp-merc-04.its.monash.edu.au/ANDS &']);


function ShowStatus(message,handles)

disp(message);
set(handles.statusText,'string',message);
drawnow;
% future work will write message to log file


% --------------------------------------------------------------------
function opendoc_getstarted_Callback(hObject, eventdata, handles)
% hObject    handle to opendoc_getstarted (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% open https://docs.google.com/a/monash.edu/file/d/0B5AwrrygtT4uX1ZiYnk0N3ZKMWM/edit
% standard MATLAB call to open url does not work on MASSIVE

system('bash -l -c "module load firefox; nohup firefox https://docs.google.com/a/monash.edu/file/d/0B5AwrrygtT4uX1ZiYnk0N3ZKMWM/edit &" - 2>&1 /dev/null');


% --------------------------------------------------------------------
function opendoc_userguide_Callback(hObject, eventdata, handles)
% hObject    handle to opendoc_userguide (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

system('bash -l -c "module load firefox; nohup firefox https://docs.google.com/a/monash.edu/file/d/0B5AwrrygtT4uQVVoVlhLRmQ3MUk/edit &" - 2>&1 /dev/null');


% --------------------------------------------------------------------
function uitable2_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to uitable2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --------------------------------------------------------------------
function showmetadata_Callback(hObject, eventdata, handles)
% hObject    handle to showmetadata (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
ShowStatus('Show Metadata of dataset. ',handles);
Selection = handles.DatasetSelection;
if isempty(Selection) %|| length(Selection) > 3
    ShowStatus('No dataset selected or too many',handles);
    return
else
    
    table = get(handles.uitable2,'Data');
    curProj =handles.currentProject;
    if ~isempty(char(table{Selection(1),handles.TABLE_COL.CID}))
        DatasetID = [char(curProj) '.' char(table{Selection(1),handles.TABLE_COL.CID})];
        [status listing] = GetDarisMetaData(DatasetID );
        if status ~= 0
            ShowStatus('Error in getting metadata.',handles);
        else
            %            msgbox(listing,'Xglom Dataset Metadata')
            
            hMeta=figure(                'menubar'                       , 'none', ...
                'toolbar'                       , 'none', ...
                'resize'                        , 'off', ...
                'Name' , 'Daris Metadata');
            figPos = get(hMeta,'position');
            uicontrol(...
                'style'                     , 'listbox', ...
                'backgroundcolor'           , 'white', ...
                'position',[10 10 figPos(3)-20 figPos(4)-20], ...
                'horizontalalignment'       , 'left', ...
                'fontweight'                , 'normal', ...
                'string'                    , char(listing), ...
                'parent'                    , hMeta, ...
                'tag'                       , 'statusText');     
        end
    else
        ShowStatus('Show Metatdata: no dataset ID in seclected row.',handles);
    end
end


% --------------------------------------------------------------------
function Export2Nifti_Callback(hObject, eventdata, handles)
% hObject    handle to Export2Nifti (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

ShowStatus('Running "Export2Nifti_Callback" ... ',handles);
Selection = handles.DatasetSelection;
table = get(handles.uitable2,'Data');

if isempty(Selection) || isempty(table) %|| length(Selection) > 3
    ShowStatus(' No dataset selected or table empty.',handles);
    return;
else
    
    
    curProj =handles.currentProject;
    if isempty(curProj)
        warndlg('No project selected. ', 'Xglom Warning', 'modal');
        return
    end
    
    %char(table{Selection(1),1})
    description = char(table{Selection(1),handles.TABLE_COL.Description});
    original_filtered_str = char(table{Selection(1),handles.TABLE_COL.OrigFilt});
    
    if strcmp(original_filtered_str,'P')
        
        if isempty(char(table{Selection(1)-1,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for depth image. ', 'Xglom Warning Dialog', 'modal');
            return;
        end
        DatasetID = [char(curProj) '.' char(table{Selection(1)-1,handles.TABLE_COL.CID})];
        [img info] = GetImage(DatasetID,'P',handles);
        
    elseif strcmp(original_filtered_str,'S')
        if isempty(char(table{Selection(1)-2,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for output stats. ', 'Xglom Warning', 'modal');
            return;
        end
        
        DatasetID = [char(curProj) '.' char(table{Selection(1)-2,handles.TABLE_COL.CID})];
        [img info] = GetImage(DatasetID,'S',handles);
    else
        if isempty(char(table{Selection(1),handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for dataset image. ', 'Xglom Warning', 'modal');
            return;
        end
        DatasetID = [char(curProj) '.' char(table{Selection(1),handles.TABLE_COL.CID})];
        
        switch handles.SelectionModality
            case 3
                % Call VM GUI
 warndlg('Export2Nifti does not work for VM images. ', 'Xglom Warning', 'modal');                
 return;
 
            case 2
                % CT pipeline
                [img info] = GetImage(DatasetID,'CT',handles);               
            case 1
                % MR pipeline
                [img info] = GetImage(DatasetID,'MR',handles);
        end
    end
    
end
resolution = GetResolution(DatasetID,handles.LocalCache);
Export2Nifti(img, resolution);
ShowStatus('Export to NIFTI complete.',handles);

    
    
    
% --------------------------------------------------------------------
function Export2Tiff_Callback(hObject, eventdata, handles)
% hObject    handle to Export2Tiff (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

ShowStatus('Running "Export2Tiff_Callback" ... ',handles);
Selection = handles.DatasetSelection;
table = get(handles.uitable2,'Data');

if isempty(Selection) || isempty(table) %|| length(Selection) > 3
    ShowStatus(' No dataset selected or table empty.',handles);
    return;
else
    
    
    curProj =handles.currentProject;
    if isempty(curProj)
        warndlg('No project selected. ', 'Xglom Warning', 'modal');
        return
    end
    
    %char(table{Selection(1),1})
    description = char(table{Selection(1),handles.TABLE_COL.Description});
    original_filtered_str = char(table{Selection(1),handles.TABLE_COL.OrigFilt});
    
    if strcmp(original_filtered_str,'P')
        
        if isempty(char(table{Selection(1)-1,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for depth image. ', 'Xglom Warning Dialog', 'modal');
            return;
        end
        DatasetID = [char(curProj) '.' char(table{Selection(1)-1,handles.TABLE_COL.CID})];
        [img info] = GetImage(DatasetID,'P',handles);
        
    elseif strcmp(original_filtered_str,'S')
        if isempty(char(table{Selection(1)-2,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for output stats. ', 'Xglom Warning', 'modal');
            return;
        end
        
        DatasetID = [char(curProj) '.' char(table{Selection(1)-2,handles.TABLE_COL.CID})];
        [img info] = GetImage(DatasetID,'S',handles);
    else
        if isempty(char(table{Selection(1),handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for dataset image. ', 'Xglom Warning', 'modal');
            return;
        end
        DatasetID = [char(curProj) '.' char(table{Selection(1),handles.TABLE_COL.CID})];
        
        switch handles.SelectionModality
            case 3
                % Call VM GUI
 warndlg('Export2Tiff does not work for VM images. ', 'Xglom Warning', 'modal');                
 return;
 
            case 2
                % CT pipeline
                [img info] = GetImage(DatasetID,'CT',handles);               
            case 1
                % MR pipeline
                [img info] = GetImage(DatasetID,'MR',handles);
        end
    end
    
end
resolution = GetResolution(DatasetID,handles.LocalCache);
Export2Nifti(img, resolution);
ShowStatus('Export to TIFF complete.',handles);

    

% --------------------------------------------------------------------
function CreateReport_Callback(hObject, eventdata, handles)
% hObject    handle to CreateReport (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function ExportVolume_Callback(hObject, eventdata, handles)
% hObject    handle to ExportVolume (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function ExportVolume2VTK_Callback(hObject, eventdata, handles)
% hObject    handle to ExportVolume2VTK (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


ShowStatus('Running "Export2VTK_Callback" ... ',handles);
Selection = handles.DatasetSelection;
table = get(handles.uitable2,'Data');

if isempty(Selection) || isempty(table) %|| length(Selection) > 3
    ShowStatus(' No dataset selected or table empty.',handles);
    return;
else
    
    
    curProj =handles.currentProject;
    if isempty(curProj)
        warndlg('No project selected. ', 'Xglom Warning', 'modal');
        return
    end
    
    %char(table{Selection(1),1})
    description = char(table{Selection(1),handles.TABLE_COL.Description});
    original_filtered_str = char(table{Selection(1),handles.TABLE_COL.OrigFilt});
    
    if strcmp(original_filtered_str,'P')
        
        if isempty(char(table{Selection(1)-1,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for depth image. ', 'Xglom Warning Dialog', 'modal');
            return;
        end
        DatasetID = [char(curProj) '.' char(table{Selection(1)-1,handles.TABLE_COL.CID})];
        [img info] = GetImage(DatasetID,'P',handles);
        
    elseif strcmp(original_filtered_str,'S')
        if isempty(char(table{Selection(1)-2,handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for output stats. ', 'Xglom Warning', 'modal');
            return;
        end
        
        DatasetID = [char(curProj) '.' char(table{Selection(1)-2,handles.TABLE_COL.CID})];
        [img info] = GetImage(DatasetID,'S',handles);
    else
        if isempty(char(table{Selection(1),handles.TABLE_COL.CID}))
            warndlg('Cannot find subject id in table for dataset image. ', 'Xglom Warning', 'modal');
            return;
        end
        DatasetID = [char(curProj) '.' char(table{Selection(1),handles.TABLE_COL.CID})];
        
        switch handles.SelectionModality
            case 3
                % Call VM GUI
 warndlg('Export2Nifti does not work for VM images. ', 'Xglom Warning', 'modal');                
 return;
 
            case 2
                % CT pipeline
                [img info] = GetImage(DatasetID,'CT',handles);               
            case 1
                % MR pipeline
                [img info] = GetImage(DatasetID,'MR',handles);
        end
    end
    
end
resolution = GetResolution(DatasetID,handles.LocalCache);
Export2VTK(img, resolution);
ShowStatus('Export to VTK complete.',handles);

    
